package pattern.factory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zhang peng yang ming
 * @create 2018-07-21 11:38
 */
public class MyServer {
    public final static int PORT = 8080;
    public static void main(String[] args) throws Exception {
        System.out.println("MyHTTP listening......");
        try {
            ServerSocket server = new ServerSocket(PORT);
            while (true) {
                //获取套接字
                Socket socket =  server.accept();
                service(socket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * http服务器
     * @param socket
     * @throws Exception
     */
    public static void service(Socket socket) throws Exception{
        //获取输入流
        InputStream is = socket.getInputStream();
        Thread.sleep(500);
        //提取用户提交的数据
        byte[] buff = new byte[is.available()];
        //将读取客户端请求的数据存入buff中
        is.read(buff);
        //将字节转换成字符
        String httpReq = new String(buff,"UTF-8");
        if(httpReq != null && !httpReq.isEmpty()){
            System.out.println(httpReq);
            //解析获取到的请求参数
            String[] requests = httpReq.split("\n");
            String[] firstLines = requests[0].split(" ");
            String uri = firstLines[1];
			/*-------------------响应浏览器start-----------------------*/
            OutputStream os = socket.getOutputStream();
            if (uri.indexOf("favicon.ico")==-1) {
                if (uri.indexOf("servlet") == -1) {//响应的是静态资源
                    String respFirstLine = "HTTP/1.1 200 OK\r\n";
                    //响应头部
                    String head = "Content-Type: text/html\r\n\r\n";
                    //响应体，资源文件放在项目classes[字节码文件]下
                    InputStream fis = new FileInputStream("E:\\work\\教学\\project\\kehongborui100\\day33\\web\\register.html");
                    //输出响应的第一行
                    os.write(respFirstLine.getBytes());
                    //输出响应的头部信息
                    os.write(head.getBytes());
                    //输出响应body
                    byte[] buffos = new byte[24];
                    int len = 0;
                    //边读边写到浏览器
                    while ((len = fis.read(buffos)) != -1) {
                        os.write(buffos,0,len);
                    }
                    //关闭文件流
                    fis.close();
                }
                is.close();
				/*-------------------响应浏览器end-----------------------*/
            }
            Thread.sleep(1000);
            socket.close();
        }
    }

}
